package com.gzw.dms.activity;

import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.gzw.dms.MyApplication;
import com.gzw.dms.R;
import com.gzw.dms.UpdateManager;
import com.gzw.dms.adapter.MainViewPagerAdapter;
import com.gzw.dms.base.BaseActivity;
import com.gzw.dms.bean.AppInfo;
import com.gzw.dms.bean.Constant;
import com.gzw.dms.utils.HttpUtils;
import com.gzw.dms.utils.JsonUtil;
import com.gzw.dms.utils.T;
import com.gzw.dms.utils.UrlUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2016/3/10.
 */
public class Main2Activity extends BaseActivity implements NavigationView.OnNavigationItemSelectedListener {
    private Toolbar toolbar;
    private long exitTime=0;
    private LinearLayout lianer_tab;

    private DrawerLayout drawer;
    private MainViewPagerAdapter mainAdapter;
    private ViewPager mViewPager;
    private List<Class> lsFragment = new ArrayList<>();
    private List<ImageView> lsImageView = new ArrayList<>();
    private List<TextView> lsTextView = new ArrayList<>();
    private List<View> lsTabView = new ArrayList<>();
    private String[] titles = {"运单分配","运单待配", "运单签收", "签收查询"};
    private TextView tv_name, tv_accunt,tv_bbh;
    private Context mContext;
    private String NowVersion;
    private Intent mIntent;
    private String first;
    private int number=0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void setContentView() {
        setContentView(R.layout.activity_main2);
    }

    @Override
    protected void initViews() {
        lianer_tab = (LinearLayout) findViewById(R.id.layout_tab);

        toolbar = (Toolbar) findViewById(R.id.toolbar);
        drawer = (DrawerLayout) findViewById(R.id.drawer_layout);


        mViewPager = (ViewPager) findViewById(R.id.container);

        lsTextView.add((TextView) findViewById(R.id.tv_home));
        lsTextView.add((TextView) findViewById(R.id.tv_order));
        lsTextView.add((TextView) findViewById(R.id.tv_fj));
        lsTextView.add((TextView) findViewById(R.id.tv_my));

        lsImageView.add((ImageView) findViewById(R.id.iv_home));
        lsImageView.add((ImageView) findViewById(R.id.iv_order));
        lsImageView.add((ImageView) findViewById(R.id.iv_fj));
        lsImageView.add((ImageView) findViewById(R.id.iv_my));

        lsTabView.add(findViewById(R.id.tab_home));
        lsTabView.add(findViewById(R.id.tab_order));
        lsTabView.add(findViewById(R.id.tab_fj));
        lsTabView.add(findViewById(R.id.tab_my));
    }

    @Override
    protected void initData() {
        lianer_tab.setVisibility(View.GONE);

        mContext = this;
        toolbar.setTitle("首页");
        mIntent = getIntent();
        String  fpstste=(String)mIntent.getExtras().get("fpstste");
        first=(String)mIntent.getExtras().get("first");

        number = Integer.parseInt(fpstste);
        setSupportActionBar(toolbar);

//        lsFragment.add(Ddfp1Frager.class);
        if (number==0){
            lsFragment.add(DdfpFrmager.class);
        }else if (number==1){
            lsFragment.add(DpOrderFrmager.class);
        }else if (number==2){
            lsFragment.add(PsOrderFrmager.class);
        }else if (number==3){
            lsFragment.add(QscxOrderFrmager.class);
        }
        mainAdapter = new MainViewPagerAdapter(getSupportFragmentManager(), lsFragment);
        mViewPager.setAdapter(mainAdapter);
        setSelection(number);
//        mViewPager.setOffscreenPageLimit(4);//设置缓存view 的个数（实际有3个，缓存2个+正在显示的1个）
//        cheakUpDate();
    }

    @Override
    protected void initEvents() {
        toolbar.setNavigationOnClickListener(new myOnClick());

        mViewPager.setOnPageChangeListener(new myOnPageChangeListener());
        for (View v : lsTabView) {
            v.setOnClickListener(new mOnClick());
        }
    }

    class myOnClick implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            switch (v.getId()) {

                default:
                    Intent mIntent = new Intent();
//
//                    ActivityManager am = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
//                    List<ActivityManager.RunningTaskInfo> list = am.getRunningTasks(100);
//                    boolean isAppRunning = false;
//                    String MY_PKG_NAME = "com.gzw.dms.activity";
//                    for (ActivityManager.RunningTaskInfo info : list) {
//                        if (info.topActivity.getPackageName().equals(MY_PKG_NAME) || info.baseActivity.getPackageName().equals(MY_PKG_NAME)) {
//                            isAppRunning = true;
//                        }
//                    }
////                    mIntent.setClass(mContext, HomeActivity.class);
////                    ComponentName componentName = mIntent.resolveActivity(getPackageManager());
//                    if (isAppRunning == false) {
//                        // 说明系统中不存在这个activity\
//                        mIntent.setClass(mContext, HomeActivity.class);
//                        startActivity(mIntent);
//                        finish();
//                    }else {
//                    //把返回数据存入Intent
//                    mIntent.putExtra("result", 1);
//                    //设置返回数据
//                    setResult(3, mIntent);
//                    finish();
//            }
                    //把返回数据存入Intent
                    mIntent.putExtra("result", 1);
                    //设置返回数据
                    setResult(3, mIntent);
                    finish();
                    break;

            }
        }
    }
    class mOnClick implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            int i = 0;
            for (View v1 : lsTabView) {

                if (v1.getId() == v.getId()) {

                    mViewPager.setCurrentItem(i);
                    setSelection(i);

                }
                i++;
//                selectIndex=i;
            }
        }
    }

    class myOnPageChangeListener implements ViewPager.OnPageChangeListener {

        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {
            setSelection(position);
        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    }

    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        int id = item.getItemId();
        int i = 0;
        if (id == R.id.nav_camera) {
            i = 0;
        } else if (id == R.id.nav_gallery) {
            i = 1;
        }
        else if (id == R.id.nav_slideshow) {
            i = 2;
        }
        else if (id == R.id.nav_manage) {
            i = 3;
        }
        else if (id==R.id.nav_switchAccount){
            SharedPreferences sharedPreferences = getSharedPreferences(Constant.USERINFO_KEY,
                    Context.MODE_PRIVATE);
            SharedPreferences.Editor edit = sharedPreferences.edit();
            edit.putBoolean(Constant.IS_USER_LOGIN_KEY, false);
            edit.commit();
            Intent intent=new Intent();
            intent.setClass(mContext,LoginActivity.class);
            startActivity(intent);
            finish();
            return true;
        }else if (id==R.id.nav_signOut){
            SharedPreferences sharedPreferences = getSharedPreferences(Constant.USERINFO_KEY,
                    Context.MODE_PRIVATE);
            SharedPreferences.Editor edit = sharedPreferences.edit();
            edit.putBoolean(Constant.IS_USER_LOGIN_KEY, false);
            edit.commit();
            finish();
        }
        mViewPager.setCurrentItem(i);
        setSelection(i);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    private void setSelection(int index) {
        lsImageView.get(index).setSelected(true);
        lsTextView.get(index).setSelected(true);
        lsTextView.get(index).setTextColor(mContext.getResources().getColor(R.color.tab_text_pressed));
        toolbar.setTitle(titles[index]);
//
//        for (int i = 0; i < lsImageView.size(); i++) {
//            if (i == index) {
//                lsImageView.get(i).setSelected(true);
//            } else {
//                lsImageView.get(i).setSelected(false);
//            }
//        }
//        for (int i = 0; i < lsTextView.size(); i++) {
//            if (i == index) {
//                lsTextView.get(i).setSelected(true);
//                lsTextView.get(i).setTextColor(mContext.getResources().getColor(R.color.tab_text_pressed));
//            } else {
//                lsTextView.get(i).setSelected(false);
//                lsTextView.get(i).setTextColor(mContext.getResources().getColor(R.color.tab_text_normol));
//            }
//        }
//        for (int i = 0; i < titles.length; i++) {
//            if (i == index) {
//                toolbar.setTitle(titles[i]);
//            }
//        }
    }

//    @Override
//    protected void exitApp() {
//        finish();
//    }

    /**
     * 获取版本号
     * @return 当前应用的版本号
     */

    private void cheakUpDate(){
        ShowVersionTask showVersionTask = new ShowVersionTask();
        showVersionTask.execute();
    }

    public class ShowVersionTask extends AsyncTask<String, Void, String> {
        //onPreExecute方法用于在执行后台任务前做一些UI操作
        @Override
        protected void onPreExecute() {

        }

        protected String doInBackground(String... params) {
            return HttpUtils.doPost(UrlUtils.getInstance().getJavaUrl("getAppVersion"), "");
        }

        @Override
        protected void onPostExecute(final String result) {

            if (result == null || result.length() == 0) {
                T.showShort(mContext, "连接服务器异常。");
            }
            if (result.indexOf("successMsg") > 0) {
                String successMsg = JsonUtil.getMsg(result, "successMsg");
                AppInfo appInfo = JsonUtil.getPerson(successMsg, AppInfo.class);
                NowVersion=getVersion();
                if (NowVersion.equals(appInfo.getVersion())) {
//                    T.showShort(mContext, "未发现新版本");

                } else {
//                    UpdateManager mUpdateManager = new UpdateManager(mContext);
//                    mUpdateManager.checkUpdateInfo();
                }

            } else if (result.indexOf("errorMsg") > 0) {
                String errorMsg = JsonUtil.getMsg(result, "errorMsg");
                T.showShort(mContext,errorMsg);
            }
        }

    }

    /**
     * 获取版本号
     * @return 当前应用的版本号
     */
    public String getVersion() {
        try {
            PackageManager manager = this.getPackageManager();
            PackageInfo info = manager.getPackageInfo(this.getPackageName(), 0);
            String version = info.versionName;
            return version;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }



}